home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 15624 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.4 KB

  1. Path: wormer.fn.net!sysadmin@wormer.fn.net
  2. From: withheld@keepitpublic.com (Rusty Meathook)
  3. Newsgroups: comp.lang.c
  4. Subject: Reusable and Generic Functions
  5. Date: Sat, 20 Apr 1996 11:09:45 GMT
  6. Organization: Feist Connections
  7. Message-ID: <4la9k2$76o@wormer.fn.net>
  8. NNTP-Posting-Host: mark217.fn.net
  9. X-Newsreader: Forte Agent .99b.112
  10.  
  11. Suppose a guy has two linked list structures, such as:
  12.  
  13. /* Untested code based on previously written tested code :) */
  14.  
  15. typedef struct foo_tag
  16. {
  17.     int data;
  18.     struct foo_tag *next;
  19. } FOO;
  20.  
  21. typedef struct bar_tag
  22. {
  23.     float data;
  24.     struct bar_tag *next;
  25. } BAR;
  26.  
  27. /* */
  28.  
  29. Is there a simple way to handle operations on both of those lists
  30. using the same set of functions?  Say for adding links we have this
  31. function:
  32.  
  33. /* Untested code based on previously written tested code :) */
  34.  
  35. FOO *sllist_add(FOO *next, int data)
  36. {
  37.     FOO *temp;
  38.  
  39.     temp = (FOO *)malloc(sizeof(FOO));
  40.  
  41.     if (temp == NULL)
  42.     {
  43.         fprintf(stderr, "\nOut of memory in sllist_add()!\n");
  44.         return (NULL);
  45.     }
  46.  
  47.     temp->data = data;
  48.     temp->next = next;
  49.  
  50.     return (temp);
  51. }
  52.  
  53. /* */
  54.  
  55. I realize I could (feasibly) use void pointers for data and function
  56. pointers for filling in the data, but that wouldn't really simplify
  57. things; I might as well just write seperate function libraries for
  58. each different linked list structure.
  59.  
  60. My question is if there is a simple (read: elegant) way to handle like
  61. data structures with unlike data, with a single set of reusable,
  62. generic, Ansi C functions.
  63.  
  64.